// import {downFile, getSidByDefKey, downFileNew, previewOnline} from "@/api/approve/approve";
import { getSidByDefKey, downFileNew } from "@/api/approve/approve";
import {getLocalStorage} from "@/utils/localstore";
import {message} from "ant-design-vue";
import getRequest from "@/server/getRequest";
import {getMenuList} from "@/api/menu/menu";
import router from "@/router"
import { downFile } from "@/utils/getFiles"
export function getWindowDate() {
    const windowDate = new Date();
    return {
        year: windowDate.getFullYear(),
        month: windowDate.getMonth(),
        time: windowDate.getTime(),
    }
}
function getTextWidth(str) {
    let width = 0
    const html = document.createElement('span')
    const body = document.querySelector('body');
    const lengthWidth = document.querySelector('.lengthWidth')
    html.innerText = str
    html.className = 'lengthWidth'
    body && body.appendChild(html)
    width = lengthWidth && lengthWidth.offsetWidth
    lengthWidth && lengthWidth.remove()
    return width
}

export const getParams = (() => {
    const url = window.location.href.toString()
    let splitUrl = url.split('?')
    if (typeof (splitUrl[1]) === "string") {
        splitUrl = splitUrl[1].split('&')
        const params = {}
        for (let i = 0; i < splitUrl.length; i++) {
            const j = splitUrl[i].split('=')
            params[j[0]] = j[1]
        }

        return params
    } else {
        return {}
    }
})

export const renderAntTreeSelectData = (dataSource, originalTitle = 'text', originalValue = 'id', fatherDisable) => {
    return dataSource.map(tree => {
        if (tree.children && tree.children.length > 0) {
            tree.disabled = fatherDisable
            tree.title = tree[originalTitle]
            tree.value = tree[originalValue]
            renderAntTreeSelectData(tree.children, originalTitle, originalValue, fatherDisable)
        } else {
            tree.disabled = !fatherDisable
            tree.title = tree[originalTitle]
            tree.value = tree[originalValue]
        }
        return tree
    })
}

export const renderTableColumnsData = async (value, options, columnSelectOptions, program) => {
    const programNameOptions = options.find((item) => item.programName === value)
    const tableColumn = {
        bMoney: 0,

        budgetYear: getWindowDate().year,
        budgetId: '',
        budgetType: '',
        buyCategoryGuid: '',
        buyCategoryCode: '',
        buyCategoryName: '',
        buyCatalogGuid: '',
        buyCatalogCode: '',
        buyCatalogName: '',
        budgetCategoryGuid: '',
        budgetCategoryName: '',
        budgetCategoryCode: '',
        budgetCategoryText: '',

        detailId: '',
        divisionGuid: '',
        divisionName: '',

        enterpriseKind: columnSelectOptions.enterpriseKind,
        enterpriseGuid: columnSelectOptions.enterpriseGuid,
        enterpriseName: columnSelectOptions.enterpriseName,
        enterpriseText: columnSelectOptions.enterpriseName,
        enterpriseCode: columnSelectOptions.enterpriseIsbnCode,
        enterpriseKindName: columnSelectOptions.enterpriseKindName,
        economySectionGuid: '',
        economySectionName: '',
        economySectionCode: '',
        economySectionText: '',
        ecoGovGuid: '',
        ecoGovName: '',
        ecoGovCode: '',
        ecoGovText: '',


        functionSectionCode: '',
        functionSectionGuid: '',
        functionSectionName: '',

        isBuy: '0',
        isLockedText: '可调整',

        programGuid: '',
        programName: '',
        programCode: '',
        programTypeCode: '',
        programTypeGuid: '',
        programTypeName: '',
        projectName: value,

        resourceCateGuid: '',
        resourceCateCode: '',
        resourceCateName: '',

        sourceEnterpriseId: '',
        sourceFileId: '',
        sourceEconomySectionId: '',

        RN: getWindowDate().time,
        ...programNameOptions,
        ...program
    }
    return [tableColumn]
}

export const findMenuKey = (menuArray, menuFilterString, filterString) => {
    const filterMenu = []
    const forEachMenu = (menu = menuArray) => {
        menu.forEach(menuList => {
            if (menuList.children && menuList.children.length > 0) {
                filterMenu.push(menuList)
                forEachMenu(menuList.children)
            } else {
                filterMenu.push(menuList)
            }
        })
    }
    forEachMenu()
    return filterMenu.find(item => item[menuFilterString] === filterString)
}

export const findFirstMenu = (menuList) => {
    const flattenMenu = [];
    const flatten = (menu = menuList) => {
        menu.forEach(item => {
            if (item.children && item.children.length > 0) {
                flattenMenu.push(item);
                flatten(item.children);
            } else {
                flattenMenu.push(item);
            }
        });
    };
    flatten();
    return flattenMenu;
};

export const findFlattenParent = (menuList) => {
    const flattenMenu = [];
    const flatten = (menu = menuList) => {
        menu.forEach(item => {
            if (item.children && item.children.length > 0) {
                flatten(item.children);
            } else {
                flattenMenu.push(item);
            }
        });
    };
    flatten();
    return flattenMenu;
}

export const budgetOrigin = (budgetOrigin, budgetString = 'budgetType') => {
    return budgetOrigin.findIndex(item => item[budgetString]) === -1 ? budgetOrigin : budgetOrigin.length > 1 && budgetOrigin.filter(item => item[budgetString])
        .map(tableItem => {
            let sumBudgetMoney = 0;
            budgetOrigin.filter(originItem => originItem.budgetId === tableItem.budgetId && !originItem[budgetString])
                .map(filterOriginTable => {
                    sumBudgetMoney += Number(filterOriginTable.bMoney);
                    return filterOriginTable;
                })
            tableItem.bMoney = sumBudgetMoney;
            return tableItem;
        }).concat(budgetOrigin.filter(item => !item[budgetString]));
}

export async function windowDownFile(item) {
    await downFileNew({
        id: item.id,
        fileName: item.saveName
    }).then(res=>{
        const blob = res.data;
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        // onload当读取操作成功完成时调用
        reader.onload =  (e)=> {
            const a = document.createElement('a');
            // 获取文件名fileName
            a.download = item.saveName;
            a.href = e.target.result;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
    })
}

export async function windowExamineFile(item) {
    if (item.type === 'view') {
        const BASE_URL = await getRequest
        const urlBase = BASE_URL.data.ApiUrl
        window.open(`${urlBase}/onlinePreview?fileId=${encodeURIComponent(item.id)}`)
    } else {
        const {id, originName} = item;
        const requestData = {
            id,
            saveName: originName,
            originName
        }
        downFile(requestData)
    }
}

export async function windowOpenBusiness(record, flag) {
    const { typeByc } = record;
    let { formGuid } = record;
    if (JSON.parse(getLocalStorage('guidList')).length > 0 || getLocalStorage('roleId') !== '303') {
        await getSidByDefKey({
            key: record.defKey
        }).then(res => {
            const {success, data} = res
            if (success) {
                const str = `&isPrint=${typeByc === "打印"}`;
                const rejectBtn = `&rejectBtn=${typeByc === "办理"}`;
                const {path, sId, tableId, fileType} = data
                //业务中心传tabs默认selectKeys
                const tabsPath = `&tabsPath=${window.location.hash.split("#").join("")}`
                const {subject: title, instId, defId, status, taskId, nodeId, name, assigneeId, assigneeNames} = record
                if (!formGuid) {
                    formGuid = record.bizKey
                } else {
                    //从消息通知打开
                    formGuid = record.formGuid
                    const {isDone} = record
                    if (isDone === 1) {
                        flag = 1
                    }
                }
                // const {subject: title, bizKey: formGuid, instId, defId, status, taskId, nodeId, name, assigneeId, assigneeNames} = record
                // window.open(`#${path}?title=${title}&formGuid=${formGuid}&instId=${instId}&sId=${sId}&defId=${defId}&status=${status}&flag=${flag}&tableId=${tableId}&taskId=${taskId}&nodeId=${nodeId}&name=${name}&assigneeId=${assigneeId}&assigneeNames=${assignName}&fileType=${fileType}${str}${rejectBtn}${tabsPath}`)
                window.open(`#${path}?title=${title}&formGuid=${formGuid}&instId=${instId}&sId=${sId}&defId=${defId}&status=${status}&flag=${flag}&tableId=${tableId}&taskId=${taskId}&nodeId=${nodeId}&name=${name}&assigneeId=${assigneeId}&assigneeNames=${assigneeNames}&fileType=${fileType}${str}${rejectBtn}${tabsPath}`)
            } else {
                message.warning('获取流程失败')
            }
        })
    } else {
        message.warning('该用户没有绑定金财账号请绑定金财账号')
    }
}

export function getMaxLength(arr) {
    return arr.reduce((acc, item) => {
        if (item) {
            const length = getTextWidth(item)
            if (acc < length) {
                acc = length
            }
        }
        return acc
    }, 0)
}
export function getFirstMenuRouter(obj) {
    getMenuList(obj).then(res=>{
        const {data, success} = res
        const {state, roleId} = obj
        if (success) {
            const resObj = data[0].children[0]
            const {path, title, flag, fileType} = resObj
            router.push({
                path,
                query: {
                    state,
                    roleId,
                    title,
                    flag,
                    fileType,
                  }
            })
        }
    })
  }





